package com.elitesland.core.config.audit;

import com.elitesland.core.base.BaseModel;
import com.elitesland.core.constant.CommonConstant;
import com.elitesland.security.service.entity.JwtUserDto;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.time.LocalDateTime;

/**
 * 审计处理器.
 *
 * @author Kaiser（wang shao）
 * @date 2021-03-04
 */
public class CustomAuditHandler {

    /**
     * 审计前的操作
     *
     * @param obj 新增对象
     */
    public void prePersist(Object obj) {
        if (obj instanceof BaseModel) {
            Object user = currentUser();
            if (user == null) {
                return;
            }

            BaseModel entity = (BaseModel) obj;
            if (user instanceof JwtUserDto) {
                JwtUserDto userDTO = (JwtUserDto) user;
                entity.setCreateUserId(userDTO.getUser().getId());
                entity.setCreator(userDTO.getUsername());
                entity.setCreateTime(LocalDateTime.now());
            }
            entity.setDeleteFlag(CommonConstant.COMMON_DELETE_NO);
        }
    }

    /**
     * 更新前的操作
     *
     * @param obj 更新对象
     */
    public void preUpdate(Object obj) {
        beforeUpdate(obj);
    }

    /**
     * 删除前的操作
     *
     * @param obj 删除对象
     */
    public void preRemove(Object obj) {
        if (obj instanceof BaseModel) {
            beforeUpdate(obj);

            ((BaseModel) obj).setDeleteFlag(CommonConstant.COMMON_DELETE_YES);
        }
    }

    /**
     * 获取当前用户
     *
     * @return 用户信息
     */
    private Object currentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return null;
        }
        return authentication.getPrincipal();
    }

    /**
     * 修改前的操作
     *
     * @param obj 修改对象
     */
    private void beforeUpdate(Object obj) {
        if (obj instanceof BaseModel) {
            Object user = currentUser();
            if (user == null) {
                return;
            }

            BaseModel entity = (BaseModel) obj;
            if (user instanceof JwtUserDto) {
                JwtUserDto userDTO = (JwtUserDto) user;
                entity.setModifyUserId(userDTO.getUser().getId());
                entity.setUpdater(userDTO.getUsername());
                entity.setModifyTime(LocalDateTime.now());
            }
        }
    }
}
